package com.example.clock.taskPage;

import static com.example.clock.controlClass.SqlController.addTask;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.clock.Export.ExportData;
import com.example.clock.R;
import com.example.clock.basicClass.HelpFunc;
import com.example.clock.basicClass.Plan;
import com.example.clock.basicClass.Tags;
import com.example.clock.basicClass.Task;
import com.example.clock.controlClass.DatabaseHelper;
import com.example.clock.controlClass.SqlController;
import com.example.clock.lockedPage.LockActivity;
import com.example.clock.lockedPage.MainActivity;
import com.example.clock.personalPage.PersonalPage;


import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

public class TaskActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private TaskAdapter taskAdapter;
    private List<Task> taskList;
    private TextView dateTextView;
    private DatabaseHelper databaseHelper;

    private ArrayList<Plan> plans;
    private String plansName[];
    private String primary[];

    private int primaryindex;

    private String second[][];

    ArrayAdapter<String> adapter1, adapter2, adapter4;
    private Spinner spinner2, spinner3, spinner4;

    private String buttonClicking = "";

//    String currDate;

    private boolean isStateOne = true;
    private boolean isToday=true;
    private boolean dontUpdateSpinner = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);
    }
    @Override
    protected void onStart() {

        // 初始化 DatabaseHelper
        super.onStart();
        databaseHelper = new DatabaseHelper(this, getApplicationContext());
        databaseHelper.open();

        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        primary = Tags.getStringBigTags(db);
        second = Tags.getStringSmallTags(db);


        plans = SqlController.getTodayPlans(db);
        plansName = new String[plans.size() + 1];
        plansName[0] = "自定义任务";
        for (int i = 0; i < plans.size(); i++) {
            Plan plan = plans.get(i);
            plansName[i + 1] = plan.getPlanName();
        }


        Log.d("my", "onCreate: " + plans.get(0).getPlanName());
        Log.d("my", "onCreate: " + Arrays.toString(plansName));
        Log.d("my", "onCreate: " + plansName[0]);
        Log.d("my", "onCreate: " + plansName[1]);

        recyclerView = findViewById(R.id.recyclerView);
//        taskList = createDummyTasks();
//        taskList=getTaskList();
        taskList = oriGetTaskList();

        taskAdapter = new TaskAdapter(taskList);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(taskAdapter);

        dateTextView = findViewById(R.id.dateTextView);
        updateDateText(Calendar.getInstance());
        dateTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int before, int count) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String dateString = editable.toString();

                // 使用 SimpleDateFormat 解析日期字符串
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                try {
                    Date selectedDate = dateFormat.parse(dateString);

                    // 获取当前日期
                    Date currentDate = new Date();

                    // 将日期转换为字符串以便比较
                    String currentDateStr = dateFormat.format(currentDate);
                    String selectedDateStr = dateFormat.format(selectedDate);

                    // 判断是否是今天的日期
                    if (currentDateStr.equals(selectedDateStr)) {
                        isToday = true;
                    } else {
                        isToday = false;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                updateTaskDataInUI();
                updateUI(isStateOne);
            }
        });


        Button taskLeftButton = findViewById(R.id.taskLeftButton);
        Button taskRightButton = findViewById(R.id.taskRightButton);
        taskLeftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buttonClicking = "left";
                if (isStateOne) {
                    showInputDialog();
                } else {
//                    结束事件
                    databaseHelper.finishLastThing();
                    updateTaskDataInUI();
                    isStateOne = !isStateOne;
                    updateUI(isStateOne);
                }


            }
        });

        taskRightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buttonClicking = "right";
                showInputDialog();
            }
        });


    }


    @Override
    protected void onResume() {
        super.onResume();
        updateTaskDataInUI();
    }

    private void showInputDialog() {
        // 创建一个AlertDialog.Builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("创建事件");

        // 设置AlertDialog的布局
        View view = getLayoutInflater().inflate(R.layout.task_dialog_input_layout, null);
        builder.setView(view);

        // 获取AlertDialog中的控件
        EditText taskNameEditText = view.findViewById(R.id.editTextTaskName);

        EditText taskDescriptionEditText = view.findViewById(R.id.editTextTaskDescription);

        EditText taskPlanLastTimeEditText = view.findViewById(R.id.editTextTaskPlanLastTime);

        if (Objects.equals(buttonClicking, "left")) {
            taskPlanLastTimeEditText.setVisibility(View.INVISIBLE);
        } else if (Objects.equals(buttonClicking, "right")) {
            taskPlanLastTimeEditText.setVisibility(View.VISIBLE);
        }


        spinner2 = (Spinner) view.findViewById(R.id.spinnerBigTagTask);
        adapter1 = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, primary);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(adapter1);


            spinner3 = (Spinner) view.findViewById(R.id.spinnerSmallTagTask);
             adapter2 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, HelpFunc.deleteEmptyElementinArray(second[0]));
            adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner3.setAdapter(adapter2);

        spinner4 = (Spinner) view.findViewById(R.id.spinnerPlan);
        adapter4 = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, plansName);
        adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner4.setAdapter(adapter4);

        spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {


                if (position == 0) {
                    dontUpdateSpinner=false;
                    taskNameEditText.setEnabled(true);
                    spinner2.setEnabled(true);
                    spinner3.setEnabled(true);
                } else {
                    Plan plan = plans.get(position - 1);
                    String planLargeTag = plan.getLargeTags();
                    String planSmallTag = plan.getSmallTags();
                    String planName = plan.getPlanName();

                    dontUpdateSpinner = true;

                    adapter1 = (ArrayAdapter<String>) spinner2.getAdapter();
                    int largeTagPosition = adapter1.getPosition(planLargeTag);
                    spinner2.setSelection(largeTagPosition);

                    try {
                        adapter2 = new ArrayAdapter<>(TaskActivity.this, android.R.layout.simple_spinner_dropdown_item, HelpFunc.deleteEmptyElementinArray(second[largeTagPosition]));
                        spinner3.setAdapter(adapter2);
                    } catch (Exception e) {

                    }

                    adapter2 = (ArrayAdapter<String>) spinner3.getAdapter();
                    int smallTagPosition = adapter2.getPosition(planSmallTag);
                    spinner3.setSelection(smallTagPosition);

                    EditText taskNameEditText = view.findViewById(R.id.editTextTaskName);
                    taskNameEditText.setText(planName);

//                    dontUpdateSpinner=false;

                    taskNameEditText.setEnabled(false);
                    spinner2.setEnabled(false);
                    spinner3.setEnabled(false);


                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // 当没有项被选中时触发的代码
            }
        });


            spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if(!dontUpdateSpinner) {
                        primaryindex = position;
                        adapter2 = new ArrayAdapter<>(TaskActivity.this, android.R.layout.simple_spinner_dropdown_item, HelpFunc.deleteEmptyElementinArray(second[position]));
                        spinner3.setAdapter(adapter2);
                    }
                    else {
                        dontUpdateSpinner=false;
                    }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }

        });

        String confirmText = "确认";

        if (Objects.equals(buttonClicking, "left")) {
            confirmText = "开始事件";
        } else if (Objects.equals(buttonClicking, "right")) {
            confirmText = "开始锁屏";
        }

        // 设置AlertDialog的确定按钮点击事件
        builder.setPositiveButton(confirmText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 在确定按钮点击事件中获取用户输入的内容，并创建Task对象
                String taskName = taskNameEditText.getText().toString();
                String taskDescription = taskDescriptionEditText.getText().toString();
                int planTime = 30;
                if (!(taskPlanLastTimeEditText.getText().toString().equals(""))) {
                    planTime = Integer.parseInt(taskPlanLastTimeEditText.getText().toString());
                }
                //                判断不合法输入
                if(taskName.equals("") ){
                    Toast.makeText(TaskActivity.this, "事件名不可为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                else if (planTime ==0){
                    Toast.makeText(TaskActivity.this, "持续时间不可为0或空！", Toast.LENGTH_SHORT).show();
                    return;
                }

                Date currentDate = new Date();

                // 定义日期和时间格式
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

                // 格式化日期和时间
                String formattedDate = dateFormat.format(currentDate);
                String formattedTime = timeFormat.format(currentDate);


                // 组装Task对象
                Task newTask = new Task();

                Object selectedItem2 = spinner2.getSelectedItem();
                String selectedString2 = (String) selectedItem2;
                Object selectedItem3 = spinner3.getSelectedItem();
                String selectedString3 = (String) selectedItem3;
//                自定义Task时PlanId为0
                if (spinner4.getSelectedItemPosition() == 0) {
                    newTask.setPlanId("0");
                } else {
                    Plan plan = plans.get(spinner4.getSelectedItemPosition() - 1);
                    newTask.setPlanId(plan.getPlanId());
                }

                newTask.setTaskName(taskName);
                newTask.setTips(taskDescription);
                newTask.setDate(formattedDate);
                newTask.setStartTime(formattedTime);
                newTask.setLargeTags(selectedString2);
                newTask.setSmallTags(selectedString3);
                newTask.setEndTime("~~:~~:~~");
                newTask.setPlanTime(planTime);

//                开始任务
                if (Objects.equals(buttonClicking, "left")) {
                    DatabaseHelper dbhelper = new DatabaseHelper(TaskActivity.this, TaskActivity.this);
                    SQLiteDatabase db = dbhelper.getReadableDatabase();

                    addTask(db, newTask);

                    Toast.makeText(TaskActivity.this, "成功创建任务", Toast.LENGTH_SHORT).show();
//                    更新页面数据

                    updateTaskDataInUI();

                    isStateOne = !isStateOne;
                    updateUI(isStateOne);
                }
//                开始锁屏
                else if (Objects.equals(buttonClicking, "right")) {
                    Intent intent = new Intent(TaskActivity.this, com.example.clock.lockedPage.LockActivity.class);
                    intent.putExtra("Serializable", newTask);
                    startActivity(intent);
                }

            }
        });

        // 设置AlertDialog的取消按钮点击事件
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 取消按钮点击事件
                dialog.dismiss();
            }
        });

        // 创建并显示AlertDialog
        builder.create().show();
    }

    @SuppressLint("Range")
    private List<Task> getTaskList() {
        List<Task> tasks = new ArrayList<>();

        List<Task> taskList = new ArrayList<>();
        // 查询所有Task数据
        Cursor cursor = databaseHelper.getAllTasks(dateTextView.getText().toString());


        // 处理查询结果
        if (cursor.moveToFirst()) {
            do {
                Task task = new Task();

                task.setTaskId(cursor.getString(cursor.getColumnIndex("taskId")));
                task.setTaskName(cursor.getString(cursor.getColumnIndex("taskName")));
                task.setTips(cursor.getString(cursor.getColumnIndex("tips")));
                task.setDate(cursor.getString(cursor.getColumnIndex("date")));
                task.setStartTime(cursor.getString(cursor.getColumnIndex("startTime")));
                task.setEndTime(cursor.getString(cursor.getColumnIndex("endTime")));
                task.setLastTime(cursor.getInt(cursor.getColumnIndex("lastTime")));
                task.setPlanTime(cursor.getInt(cursor.getColumnIndex("planTime")));
                task.setLargeTags(cursor.getString(cursor.getColumnIndex("largeTags")));
                task.setSmallTags(cursor.getString(cursor.getColumnIndex("smallTags")));
                task.setPlanId(cursor.getString(cursor.getColumnIndex("planId")));
                task.setClockedTask(cursor.getInt(cursor.getColumnIndex("clockedTask")));
                task.setClockedMode(cursor.getInt(cursor.getColumnIndex("clockedMode")));
                task.setUnlocked(cursor.getInt(cursor.getColumnIndex("unlocked")));

                taskList.add(task);
            } while (cursor.moveToNext());
        }


        // 关闭Cursor
        cursor.close();

        return taskList;

//        return tasks;
    }

    @SuppressLint("Range")
    private List<Task> oriGetTaskList() {
        List<Task> tasks = new ArrayList<>();

        List<Task> taskList = new ArrayList<>();
        // 查询所有Task数据

        Date currentDate = new Date();

        // 定义日期和时间格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 格式化日期和时间
        String formattedDate = dateFormat.format(currentDate);

        Cursor cursor = databaseHelper.getAllTasks(formattedDate);


        // 处理查询结果
        if (cursor.moveToFirst()) {
            do {
                Task task = new Task();

                task.setTaskId(cursor.getString(cursor.getColumnIndex("taskId")));
                task.setTaskName(cursor.getString(cursor.getColumnIndex("taskName")));
                task.setTips(cursor.getString(cursor.getColumnIndex("tips")));
                task.setDate(cursor.getString(cursor.getColumnIndex("date")));
                task.setStartTime(cursor.getString(cursor.getColumnIndex("startTime")));
                task.setEndTime(cursor.getString(cursor.getColumnIndex("endTime")));
                task.setLastTime(cursor.getInt(cursor.getColumnIndex("lastTime")));
                task.setPlanTime(cursor.getInt(cursor.getColumnIndex("planTime")));
                task.setLargeTags(cursor.getString(cursor.getColumnIndex("largeTags")));
                task.setSmallTags(cursor.getString(cursor.getColumnIndex("smallTags")));
                task.setPlanId(cursor.getString(cursor.getColumnIndex("planId")));
                task.setClockedTask(cursor.getInt(cursor.getColumnIndex("clockedTask")));
                task.setClockedMode(cursor.getInt(cursor.getColumnIndex("clockedMode")));
                task.setUnlocked(cursor.getInt(cursor.getColumnIndex("unlocked")));

                taskList.add(task);
            } while (cursor.moveToNext());
        }


        // 关闭Cursor
        cursor.close();

        return taskList;

//        return tasks;
    }

    public void showDatePickerDialog(View view) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int selectedYear, int monthOfYear, int dayOfMonth) {
                        Calendar selectedDate = Calendar.getInstance();
                        selectedDate.set(selectedYear, monthOfYear, dayOfMonth);
                        updateDateText(selectedDate);
                    }
                },
                year, month, day);

        // 显示日期选择对话框
        datePickerDialog.show();
    }

    private void updateDateText(Calendar calendar) {
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，需要加1
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        @SuppressLint("DefaultLocale") String dateText = String.format("%d-%02d-%02d", year, month, day);

//        String dateText = "ahiudhiuwdhiawhd";
        dateTextView.setText(dateText);
    }

    private void updateTaskDataInUI() {
        taskList = getTaskList();
        taskAdapter = new TaskAdapter(taskList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerView.setAdapter(taskAdapter);
    }

    private void updateUI(boolean isStateOne) {

        Button taskLeftButton = findViewById(R.id.taskLeftButton);
        Button taskRightButton = findViewById(R.id.taskRightButton);

        if(!isToday){
            taskLeftButton.setVisibility(View.INVISIBLE);
            taskRightButton.setVisibility(View.INVISIBLE);
        }else {
            if (isStateOne) {
                taskLeftButton.setText("开始事件");
                taskLeftButton.setBackgroundColor(ContextCompat.getColor(this, R.color.task_button_state_1));
                taskLeftButton.setBackgroundTintList(getResources().getColorStateList(R.color.green));
                taskLeftButton.setVisibility(View.VISIBLE);
                taskRightButton.setVisibility(View.VISIBLE);

            } else {
                taskLeftButton.setText("结束事件");
                taskLeftButton.setBackgroundColor(ContextCompat.getColor(this, R.color.task_button_state_2));
                taskLeftButton.setBackgroundTintList(getResources().getColorStateList(R.color.pink));
                taskLeftButton.setVisibility(View.VISIBLE);
                taskRightButton.setVisibility(View.INVISIBLE);
            }
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭数据库连接
        databaseHelper.close();
    }

    public void toPagePersonal(View view) {
        Intent intent = new Intent(TaskActivity.this, PersonalPage.class);
        startActivity(intent);
    }



}